#coding:utf-8
'''
    web 页面自功能
'''
from flask_restful import Resource, request
from flask import jsonify
from _sys.function import create_code_img, admin_open_ips, had_power, parse_param_info, format_words, allow_cross, \
    create_serial_num, get_visitor_ip_addr
from _sys.models import ResponseJson, MongodbOperations, Token, CreateId, FormatIO, QiniuOperations
from _sys.parser import parsers
from _sys.code import dbNameDict

import time
import json
import cgi

responseJson = ResponseJson()
mgOp = MongodbOperations()
token = Token()
ctId = CreateId()
qiniuO = QiniuOperations()

class Dicts(object):
    '''
        建立翻译字典
    '''
    def admin(self):
        admins = mgOp.find_many(dbNameDict['adminData'], filter={})
        _dict = {}
        for admin in admins:
            _dict[admin['a_id']] = admin['a_name']
        return _dict

    def ptl(self):
        ptls = mgOp.find_many(dbNameDict['promotionalData'], filter={})
        _dict = {}
        for ptl in ptls:
            _dict[ptl['w_ptl']] = ptl['ptl_name']['cn']
        return _dict

    def product(self):
        pjs = mgOp.find_many(dbNameDict['productData'],filter={})
        _dict = {'--':'--'}
        for pj in pjs:
            _dict[pj['p_id']] = pj['p_name']['cn'] +'|'+pj['p_color']
        return _dict

    def agent(self):
        agts = mgOp.find_many(dbNameDict['agentData'],{})
        _dict = {'--': '--'}
        for agt in agts:
            _dict[agt['w_agt']] = agt['agt_name']['cn']
        return _dict

class GetDict(Resource):
    '''
        获取各项翻译词典
    '''
    @allow_cross
    def get(self):
        args = parsers()
        m = args.get('type')
        if m == 'pj':
            return responseJson.correct(code='ok', data=Dicts().product())
        if m =='ad':
            return responseJson.correct(code='ok', data=Dicts().admin())
        if m == 'ptl':
            return responseJson.correct(code='ok', data=Dicts().ptl())
        if m == 'agt':
            return responseJson.correct(code='ok', data=Dicts().agent())
        else:
            all_dict = {
                'pName': Dicts().product(),
                'admin': Dicts().admin(),
                'ptl': Dicts().ptl(),
                'agt': Dicts().agent()
            }
            return responseJson.correct(code='ok', data=all_dict)

class CodeImg(Resource):
    '''
        /w/ci
        获取验证码图片 base64
        get -- 获取验证码信息
        post -- 保留接口
        put -- 保留接口
        delete -- 保留接口
    '''
    @allow_cross
    def get(self):
        rd = create_code_img()
        return responseJson.correct(code='ok', data=rd)
    @allow_cross
    def post(self):
        return responseJson.error_response(code='RequestMethodError')
    @allow_cross
    def put(self):
        return responseJson.error_response(code='RequestMethodError')
    @allow_cross
    def delete(self):
        return responseJson.error_response(code='RequestMethodError')

class Product(Resource):
    '''
        /w/p
        产品信息接口
        get -- 获取产品信息 -- list or id(单个)  admin 提供 a_id a_token
        post --  修改产品信息（管理员） -- list or id(单个)  ip 验证
        put -- 新增产品     -- 管理员验证  ip 验证
        delete -- 删除产品  -- 超级管理员验证  ip 验证
    '''
    def __init__(self):
        self.had_power = had_power

    @allow_cross
    def get(self):
        args = parsers()
        p_id = args.get('p_id')  # 商品 pid
        p_series = args.get('p_series') #  系列
        start_t = args.get('start_t')
        end_t = args.get('end_t')
        a_id = args.get('a_id')
        a_token = args.get('a_token')

        def admin_get():
            if p_id:  # 获取单个商品
                filter = {'p_id': p_id}
                p_d = mgOp.find_one(dbNameDict['productData'], filter)  # 获取信息
                if p_d:
                    access_promotional = []
                    for i in p_d['access_promotional']:
                        access_promotional.append(Dicts().ptl()[str(i)])
                    rd = {
                        'pId': p_d['p_id'],
                        'pName': p_d['p_name'],
                        'pSeries': p_d['p_series'],
                        'pBrand': p_d['p_brand'],
                        'pColor': p_d['p_color'],
                        'accessPromotional': access_promotional,
                        'pPrice': p_d['p_price'],
                        'pImg': p_d['p_img'],
                        'pSize': p_d['p_size'],
                        'pStock': p_d['p_stock'],
                        'pCreateTime': p_d['create_time'],
                        'formatTime': p_d['format_time'],
                        'pTitle': p_d['p_title'],
                        'colorIcon':p_d['color_icon'],
                        'pSubTitle': p_d['p_sub_title'],
                        'pBriefIntro': p_d['p_brief_intro'],
                        'pCreateAdmin': Dicts().admin()[p_d['create_admin']]
                    }
                    return rd
                else:
                    return {}
            else:  # 获取商品列表
                filter = {}
                time_query = {}
                if p_series:
                    filter['p_series'] = p_series
                if start_t:
                    time_query["$gte"] = str(time.mktime(time.strptime(start_t,"%Y-%m-%d-%H:%M:%S")))
                    filter['create_time'] = time_query
                if end_t:
                    time_query["$lte"] = str(time.mktime(time.strptime(end_t,"%Y-%m-%d-%H:%M:%S")))
                    filter['create_time'] = time_query
                p_d_arr = mgOp.find_many(dbNameDict['productData'], filter, 'p_list_sort')
                rd_list = []

                for p_d in p_d_arr:
                    access_promotional = []
                    for i in p_d['access_promotional']:
                        access_promotional.append(Dicts().ptl()[str(i)])
                    tmp = {  # list 仅需要返回简要信息
                        'pId': p_d['p_id'],
                        'pName': p_d['p_name'],
                        'pSeries': p_d['p_series'],
                        'pBrand': p_d['p_brand'],
                        'pColor': p_d['p_color'],
                        'colorIcon': p_d['color_icon'],
                        'accessPromotional': access_promotional,
                        'pPrice': p_d['p_price'],
                        'pImg': p_d['p_img'],
                        'pSize': p_d['p_size'],
                        'pStock': p_d['p_stock'],
                        'formatTime': p_d['format_time'],
                        'pCreateAdmin': Dicts().admin()[p_d['create_admin']]
                    }
                    rd_list.append(tmp)
                return rd_list

        def user_get():
            pg = args.get('pg')  # 分页 default 1
            def return_product_info_by_temp(p_d):  # 处理回馈产品信息
                '''
                    返回模板
                :param p_d:
                :return:
                '''
                if type(p_d) == dict:
                    rd = {
                        'pId': p_d['p_id'],
                        'pName': p_d['p_name'],
                        'pSeries': p_d['p_series'],
                        'pBrand': p_d['p_brand'],
                        'pColor': p_d['p_color'],
                        'pBriefIntro': p_d['p_brief_intro'],
                        'accessPromotional': p_d['access_promotional'],
                        'colorIcon': p_d['color_icon'],
                        'pPrice': p_d['p_price'],
                        'pImg': p_d['p_img'],
                        'pTitle': p_d['p_title'],
                        'pSubTitle': p_d['p_sub_title'],
                        'pSize': p_d['p_size'],
                        'pStock': p_d['p_stock']
                    }
                    return rd
                if type(p_d) == list:
                    r_arr = []
                    for i in p_d:
                        rd = {
                            'pId': i['p_id'],
                            'pName': i['p_name'],
                            'pSeries': i['p_series'],
                            'pBrand': i['p_brand'],
                            'pColor': i['p_color'],
                            'pBriefIntro': i['p_brief_intro'],
                            'accessPromotional': i['access_promotional'],
                            'pPrice': i['p_price'],
                            'colorIcon': i['color_icon'],
                            'pImg': i['p_img'],
                            'pTitle': i['p_title'],
                            'pSubTitle': i['p_sub_title'],
                            'pSize': i['p_size'],
                            'pStock': i['p_stock']
                        }
                        r_arr.append(rd)
                    return r_arr

            if p_id:  # 获取单个商品
                filter = {'p_id': p_id}
                p_d = mgOp.find_one(dbNameDict['productData'], filter)  # 获取信息
                rd = return_product_info_by_temp(p_d)

                family_data = mgOp.find_many(dbNameDict['productData'],
                                             filter={'p_family_id': p_d['p_family_id']})  # 同族获取
                rd_family_data = []
                #print(family_data)
                for i in family_data:  # 同族数据处理
                    s = {}
                    s['pId'] = i['p_id']
                    s['pColor'] = i['p_color']
                    s['colorIcon'] = i['color_icon']
                    rd_family_data.append(s)

                rd['familyData'] = rd_family_data
                return rd
            else:  # 获取商品列表
                if not pg:  # 如果没有pg参数
                    pg = 1
                pg = int(pg)
                if p_series == 'all':
                    filter = {}
                else:
                    filter = {'p_series': p_series}
                p_d = mgOp.find_many(dbNameDict['productData'], filter)[
                      (pg - 1) * 16: pg * 16]  # 返回的数据 list  单页面为 16条数据
                rd = return_product_info_by_temp(p_d)
                return rd

        if a_id and a_token:
            a_ip = request.remote_addr
            p_type = args.get('p_type')
            if not token.verify(a_token, a_id):  # token 失效
                return responseJson.error_response(code='tokenFailure')

            if not admin_open_ips(a_ip):  # ip 非法
                return responseJson.error_response(code='understandRequestButRefused')

            a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']  # 管理员角色
            powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']  # 获取角色权限 list

            has_power = False
            if p_type == 'normal':
                has_power = self.had_power('CanGetNormalProductsList', powers)
            elif p_type == 'custom':
                has_power = self.had_power('CanGetCustomProductsList', powers)
            elif p_type == 'select':
                has_power = self.had_power('CanGetSelectList', powers)
            if not has_power:  # 不具有权限
                return responseJson.error_response(code='permissionsValidationFailure')

            rd = admin_get()  # 管理员获取
            return responseJson.correct(code='ok', data=rd)
        else:
            rd = user_get()   # 用户获取
            return responseJson.correct(code='ok', data=rd)
    @allow_cross
    def post(self):
        '''
            修改商品信息
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        p_price = args.get('p_price')
        p_id = args.get('p_id')
        p_stock = args.get('p_stock')
        color_icon = args.get('color_icon')
        p_title = args.get('title')  # 标题  cn:xxxxxx|en:xxxxxxx|tw:xxxxxx
        p_sub_title = args.get('sub_title')  # 副标题
        p_brief_intro = args.get('intro')  # 简介
        p_size = args.get('p_size')  # S|M|L
        p_img = args.get('p_img')  # 图片链接 url|url|url| 形式
        access_promotional = args.get('access_promotional')  # id|id|id
        p_type = args.get('p_type')  # 商品类型 normal 普通 custom 定制 select 选择

        if not token.verify(token=a_token, _id=a_id): # token 失效
            return responseJson.error_response(code='tokenFailure')

        if not admin_open_ips(a_ip):    # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id':a_id})['a_role_id']  # 管理员角色
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']    # 获取角色权限 list

        has_power = False
        if p_type == 'normal':
            has_power = self.had_power('CanModifyNormalProduct', powers)
        elif p_type == 'custom':
            has_power = self.had_power('CanModifyCustomProduct', powers)
        elif p_type == 'select':
            has_power = self.had_power('CanModifySelectProduct', powers)

        if has_power:    # 具有权限
            had = mgOp.find_one(dbNameDict['productData'], filter={'p_id': p_id}) # 检查是否已具有产品
            if not had:
                return responseJson.error_response(code='resourcesDoNotExist')  # 产品信息不存在
            else:
                new_product_data = {
                    'p_stock':p_stock,
                    'color_icon':color_icon
                }
                new_product_data['p_title'] = format_words(parse_param_info(p_title))
                new_product_data['p_sub_title'] = format_words(parse_param_info(p_sub_title))
                new_product_data['p_brief_intro'] = format_words(parse_param_info(p_brief_intro))
                new_product_data['p_size'] = parse_param_info(p_size)
                new_product_data['p_price'] = format_words(parse_param_info(p_price))
                new_product_data['p_img'] = parse_param_info(p_img)
                new_product_data['access_promotional'] = parse_param_info(access_promotional)
                if mgOp.update_one(dbNameDict['productData'], filter={'p_id':p_id},data=new_product_data):
                    return responseJson.correct(code='ok', data={'msg':'修改商品信息成功'})
        else:
            return responseJson.error_response(code='permissionsValidationFailure')  # 不具有权限



    @allow_cross
    def put(self):
        '''
            新增 产品
            token 验证
            admin 管理员权限
            ip 白名单
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        p_name = args.get('p_name')       # cn:xxxxxx|en:xxxxxxx|tw:xxxxxx
        p_series = args.get('p_series')
        p_brand = args.get('p_brand')
        p_color = args.get('p_color')
        p_price = args.get('p_price')
        p_stock = args.get('p_stock')
        color_icon = args.get('color_icon')
        p_title = args.get('title')   # 标题  cn:xxxxxx|en:xxxxxxx|tw:xxxxxx
        p_sub_title = args.get('sub_title')   # 副标题
        p_brief_intro = args.get('intro')  # 简介
        p_size = args.get('p_size')     # S|M|L
        p_img = args.get('p_img')  # 图片链接 url|url|url| 形式
        access_promotional = args.get('access_promotional')  # id|id|id
        p_type = args.get('p_type')  # 商品类型 normal 普通 custom 定制 select 选择

        if not token.verify(token=a_token, _id=a_id): # token 失效
            return responseJson.error_response(code='tokenFailure')

        if not admin_open_ips(a_ip):    # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id':a_id})['a_role_id']  # 管理员角色
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']    # 获取角色权限 list

        has_power = False
        if p_type == 'normal':
            has_power = self.had_power('CanAddNormalProduct', powers)
        elif p_type == 'custom':
            has_power = self.had_power('CanAddCustomProduct', powers)
        elif p_type == 'select':
            has_power = self.had_power('CanAddSelectProduct', powers)

        if has_power:    # 具有权限
            p_id = ctId.pid(p_brand, p_series, p_color, p_type)
            had = mgOp.find_one(dbNameDict['productData'], filter={'p_id': p_id}) # 检查是否已具有产品
            if had:
                return responseJson.error_response(code='productInformationAlreadyExisted')  # 产品信息已存在
            else:
                new_product_data = {
                    'p_id': p_id,
                    'p_type': p_type,
                    'p_stock': p_stock,
                    'p_series': p_series,
                    'p_brand': p_brand,
                    'color_icon':color_icon,
                    'create_time': str(time.time()),
                    'format_time':FormatIO().timestamp_format(time.time()),
                    'create_admin': a_id,
                    'p_family_id': ctId.pid(p_brand, p_series, p_type,'')  # 同族
                }
                new_product_data['p_name'] = format_words(parse_param_info(p_name))    # 格式化商品名 以下类推
                new_product_data['p_title'] = format_words(parse_param_info(p_title))
                new_product_data['p_sub_title'] = format_words(parse_param_info(p_sub_title))
                new_product_data['p_brief_intro'] = format_words(parse_param_info(p_brief_intro))
                new_product_data['p_color'] = p_color
                new_product_data['p_size'] = parse_param_info(p_size)
                new_product_data['p_price'] = format_words(parse_param_info(p_price))
                new_product_data['p_img'] = parse_param_info(p_img)
                new_product_data['access_promotional'] = parse_param_info(access_promotional)
                if mgOp.insert_one(dbNameDict['productData'], new_product_data):
                    return responseJson.correct(code='ok', data={'msg':'添加新商品成功'})
        else:
            return responseJson.error_response(code='permissionsValidationFailure')  # 不具有权限

    @allow_cross
    def delete(self):
        '''
            删除产品信息  -- 超级管理员权限 ip 验证
        :return:
        '''
        args = parsers()
        p_id = args.get('p_id')
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr

        if not token.verify(token=a_token, _id=a_id): # token 失效
            return responseJson.error_response(code='tokenFailure')

        if not admin_open_ips(a_ip):    # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']
        #print(p_id)
        p_type = mgOp.find_one(dbNameDict['productData'], filter={'p_id': p_id})['p_type']

        has_power = False
        if p_type == 'normal':
            has_power = self.had_power('CanAddNormalProduct', powers)
        elif p_type == 'custom':
            has_power = self.had_power('CanAddCustomProduct', powers)
        elif p_type == 'select':
            has_power = self.had_power('CanAddSelectProduct', powers)

        if not has_power:  # 不具有权限
            return responseJson.error_response(code='permissionsValidationFailure')

        if mgOp.delete_one(dbNameDict['productData'], filter={'p_id': p_id}):
            return responseJson.correct(code='ok', data={'msg':'产品信息已删除'})
        else:
            return responseJson.error_response(code='unknownError')


class Promotional(Resource):
    '''
        /w/ptl
        促销优惠活动
        get -- 获取活动 list or id
        post --修改活动内容
        put -- 新增活动项
        delete -- 删除活动
    '''

    @allow_cross
    def get(self):
        '''
            获取活动信息 list or detail
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        w_ptl = args.get('w_id')

        ptl_name = args.get('name')  # 提供status 筛选项  default  0
        ptl_type = args.get('type')   # 提供活动类型筛选项     default  all

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')
        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanGetPromotionalList', powers):  # 不具权限
            return responseJson.error_response(code='permissionsValidationFailure')

        if w_ptl:  # 获取单个活动详细信息
            ptl_data = mgOp.find_one(dbNameDict['promotionalData'], filter={'w_ptl': w_ptl})
            rd = {
                'wPtl': ptl_data['w_ptl'],
                'ptlName':ptl_data['ptl_name'],
                'ptlIntro':ptl_data['ptl_intro'],
                'ptlType':ptl_data['ptl_type'],
                'formatTime':ptl_data['format_time'],
                'createAdmin':ptl_data['create_admin'],
                'discount':ptl_data['discount'],
                'ptlStatus':ptl_data['ptl_status']
            }
            return responseJson.correct(code='ok', data=rd)
        else:   # 获取全部活动列表
            filter = {}
            if ptl_name:
                filter['ptl_name'] = ptl_name
            if ptl_type:
                filter['ptl_type'] = ptl_type
            ptl_data = mgOp.find_many(dbNameDict['promotionalData'], filter=filter)
            rd = []
            for i in ptl_data:
                _d = {
                    'wPtl': i['w_ptl'],
                    'ptlName':i['ptl_name'],
                    'ptlIntro':i['ptl_intro'],
                    'ptlType':i['ptl_type'],
                    'formatTime':i['format_time'],
                    'createAdmin':i['create_admin'],
                    'discount':i['discount'],
                    'ptlStatus':i['ptl_status']
                }
                rd.append(_d)
            return responseJson.correct(code='ok', data=rd)

    @allow_cross
    def post(self):
        '''
            修改活动详情
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        w_ptl = args.get('w_id')
        ptl_intro = args.get('intro')   # 活动描述  # cn:xxxxx|en:xxxxx|tw:xxxxxx|
        ptl_status = args.get('status')  # 活动状态
        ptl_name = args.get('name')   # cn:xxxxx|en:xxxxx|tw:xxxxxx|

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')
        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanModifyPromotional', powers):  # 不具权限
            return responseJson.error_response(code='permissionsValidationFailure')

        n_d = {}
        if ptl_intro:   # 修改活动简介
            n_d['ptl_intro'] = format_words(parse_param_info(ptl_intro))
        if ptl_name:   # 修改活动题目
            n_d['ptl_name'] = format_words(parse_param_info(ptl_name))
        if ptl_status:    # 修改活动状态
            n_d['ptl_status'] = ptl_status

        if not n_d:
            return responseJson.error_response(code='lackOfNecessaryParameters')  # 无修改项
        if mgOp.update_one(dbNameDict['promotionalData'], {'w_ptl':w_ptl}, n_d):
            return responseJson.correct(code='ok', data={'msg':'修改活动信息成功'})
        else:
            return responseJson.error_response(code='unknownError')

    @allow_cross
    def put(self):
        '''
            新增活动  同类型的活动（激活状态）只能存在一个
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        ptl_type = args.get('type')
        ptl_intro = args.get('intro')  # 活动描述  # cn:xxxxx|en:xxxxx|tw:xxxxxx|
        ptl_status = '1'  # 活动状态
        ptl_name = args.get('name')  # cn:xxxxx|en:xxxxx|tw:xxxxxx|

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')
        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanAddPromotional', powers):  # 不具权限
            return responseJson.error_response(code='permissionsValidationFailure')

        if ptl_status == '1' and mgOp.find_one(dbNameDict['promotionalData'], filter={'ptl_type': ptl_type, 'ptl_status': '1'}):
            return responseJson.error_response(code='someTypePromotionalCanOnlyBeOne')  # 同类型的活动（激活状态）只能存在一个

        ptl_data = {          # 基本信息
            'w_ptl': ctId.otherid(),
            'ptl_type':ptl_type,
            'ptl_intro': format_words(parse_param_info(ptl_intro)),
            'ptl_name': format_words(parse_param_info(ptl_name)),
            'ptl_status':ptl_status,
            'create_time': str(time.time()),
            'format_time': FormatIO().timestamp_format(time.time()),
            'create_admin': a_id
        }
        if ptl_type == 'vip' or ptl_type == 'discount':
            ptl_data['discount'] = args.get('num')

        if ptl_type == 'fullSubtraction':
            ptl_data['relief_amount'] = args.get('relief_amount')
            ptl_data['full_amount'] = args.get('full_amount')

        if ptl_type == 'deductible':
            ptl_data['full_amount'] = args.get('full_amount')

        if mgOp.insert_one(dbNameDict['promotionalData'], ptl_data):
            return responseJson.correct(code='ok', data={'msg':'添加新活动成功'})
        else:
            return responseJson.error_response(code='unknownError')

    @allow_cross
    def delete(self):
        '''
            删除活动项
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        w_ptl = args.get('w_ptl')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')
        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanDeletePromotional', powers):  # 不具权限
            return responseJson.error_response(code='permissionsValidationFailure')

        if mgOp.delete_one(dbNameDict['promotionalData'], filter={'w_ptl': w_ptl}):
            return responseJson.correct(code='ok', data={'msg': '删除活动成功'})
        else:
            return responseJson.error_response(code='resourcesDoNotExist')


class ProductSerialNumber(Resource):
    '''
        /w/psn
        商品序列号相关
        get --获取序列号信息 list or id
        post --修改单个序列号信息
        put  -- 新增序列号
        delete -- 删除单个或数个序列号
    '''
    @allow_cross
    def get(self):
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        agt_code = args.get('agt_code')
        start_t = args.get('start_t')
        end_t = args.get('end_t')
        status = args.get('status')
        code = args.get('code')   # 序列号

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')
        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanGetProductSNList', powers):  # 不具权限
            return responseJson.error_response(code='permissionsValidationFailure')

        if code:    # 单个序列号信息
            code_data = mgOp.find_one(dbNameDict['productSerialNumber'], filter={'code': code})
            code_data['create_adm_id'] = code_data['create_adm_id']
            code_data['belong'] = code_data['belong']
            return responseJson.correct(code='ok', data={'total':1,'data':[code_data]})
        else:     # 获取全部序列号 每页返回 50 条     -- 应当有个机制返回总数是多少
            filter={}
            if agt_code:
                filter['agent'] = agt_code
            if status:
                filter['status'] = status
            if start_t:
                filter['create_time'] = {"$gte": str(time.mktime(time.strptime(start_t,"%Y-%m-%d-%H:%M:%S")))}
            if end_t:
                filter['create_time'] = {"$lte": str(time.mktime(time.strptime(end_t, "%Y-%m-%d-%H:%M:%S")))}
            code_data = mgOp.find_many(dbNameDict['productSerialNumber'], filter)
            count_of_data = len(code_data)
            rds = code_data
            for rd in rds:
                rd['create_adm_id'] = rd['create_adm_id']
                rd['belong'] = rd['belong']
            return responseJson.correct(code='ok', data={ 'total': count_of_data, 'data': rds })

    @allow_cross
    def post(self):
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        code = args.get('code')  # 序列号
        status = args.get('status')
        agt_code = args.get('agt_code')
        belong = args.get('belong')
        man = args.get('man')
        size = args.get('size')
        time = args.get('time')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')
        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanDeletePromotional', powers):  # 不具权限
            return responseJson.error_response(code='permissionsValidationFailure')

        new_data = {}
        if status:
            new_data['status'] = status
        if agt_code:
            new_data['agent'] = agt_code
        if belong:
            new_data['belong'] = belong
        if man:
            new_data['salesman'] = man
        if time:
            new_data['used_time'] = time
        if size:
            new_data['size'] = size
        #print(new_data)
        try:
            mgOp.update_one(dbNameDict['productSerialNumber'], filter={'code':code}, data=new_data)
            return responseJson.correct(code='ok', data={'msg':'修改序列号信息成功'})
        except Exception:
            return responseJson.error_response(code='unknownError')

    @allow_cross
    def put(self):
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        num = args.get('num')  # 数量
        agt_code = args.get('agt_code')    # agt id      可空
        p_id = args.get('belong')     # 所属商品      可空
        p_size = args.get('size')   # 所属商品 型号  可空

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')
        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanAddProductSN', powers):  # 不具权限
            return responseJson.error_response(code='permissionsValidationFailure')

        codes = create_serial_num(int(num))

        put_data = []
        for code in codes:
            n = {
                'code': code,
                'status':'0',   # 目前无意义
                'belong':p_id,
                'sales_man':'--',
                'used_time': '--',
                'agent': agt_code,    # 代理id
                'size':p_size,
                'create_adm_id':a_id,
                'active_time':'--',  # 激活时间
                'create_time': str(time.time()),
                'format_time':FormatIO().timestamp_format(time.time()),
                'query_time': time.strftime("%Y-%m-%d", time.localtime(time.time()))
            }
            qiniuO.upload_qr_code(code)
            qiniuO.upload_barcode(code)
            put_data.append(n)

        if mgOp.insert_many(dbNameDict['productSerialNumber'], put_data):    # 成功新增
            return responseJson.correct(code='ok', data={'msg': '新增商品序列号成功'})
        else:
            return responseJson.error_response(code='unknownError')    # 失败

    @allow_cross
    def delete(self):
        return responseJson.error_response(code='RequestMethodError')


class HotCommend(Resource):
    '''
        热推--热推轮播
    '''
    @allow_cross
    def get(self):
        '''
            获取热推表格
        :return:
        '''
        args = parsers()
        try:
            rd = mgOp.find_many(dbNameDict['productData'], filter={'is_commend':'1'})
            return responseJson.correct(code='ok', data=rd)
        except Exception:
            return responseJson.error_response(code='unknownError')

    @allow_cross
    def post(self):
        return responseJson.error_response(code='RequestMethodError')

    @allow_cross
    def put(self):
        return responseJson.error_response(code='RequestMethodError')

    @allow_cross
    def delete(self):
        return responseJson.error_response(code='RequestMethodError')





class UploadImg(Resource):
    '''
    /w/upload
    '''
    def post(self):
        '''
            提供图片上传接口 --转七牛云
        :return:
        '''
        a_ip = request.remote_addr
        file = request.files.get('file')
        hexHash = request.form['hexHash']
        file_ext = request.form['fileExt']
        storage_path = request.form['storage']
        a_id = request.files.get('aId')
        a_token = request.files.get('aToken')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')
        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        rd = qiniuO.upload_img(file, hexHash, file_ext, storage_path)   # 同时文件被本地存储

        if rd:
            return responseJson.correct(code='ok',data=rd)
        else:
            return responseJson.error_response(code='unknownError')

    def get(self):
        return responseJson.error_response(code='RequestMethodError')

    def put(self):
        return responseJson.error_response(code='RequestMethodError')

    def delete(self):
        return responseJson.error_response(code='RequestMethodError')


class userIPLocation(Resource):
    def __init__(self):
        pass

    def get(self):
        a_ip = request.remote_addr
        res = get_visitor_ip_addr(a_ip)
        if res:
            return responseJson.correct(code='ok', data=res)
        return responseJson.error_response(code='unknownError')




